package mywebsocket;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import util.HTMLFilter;
@WebServlet(urlPatterns = "/chat.ws")
public class Chat extends WebSocketServlet implements SessionAware{

	public Logger logger=Logger.getLogger(Chat.class.getName());
	private int number=0;
	private Map session;
    private final Set<ChatMessageInbound> connections =
            new CopyOnWriteArraySet<ChatMessageInbound>();
   
	@Override
	protected StreamInbound createWebSocketInbound(String arg0,
			HttpServletRequest request) {
		// TODO Auto-generated method stub
		logger.info("request ws servlet");
//		System.out.println("name:"+name);
		request.getSession().setAttribute("name", "bin381");
		//System.out.println(ServletActionContext.getRequest().getSession().getAttribute("username"));
//		System.out.println("In chat username:"+(String )request.getParameter("name"));
		//System.out.println("In chat username session:"+(String )session.get("name"));
//		System.out.println("In chat username:"+(String)request.getSession().getAttribute("username"));
		String name=(String )request.getParameter("name");
		return new ChatMessageInbound(name);
	}
	private final class ChatMessageInbound extends MessageInbound{
		private final String nickName;
		public ChatMessageInbound(String name){
			this.nickName=name;
		}
		@Override
        protected void onOpen(WsOutbound outbound) {
            connections.add(this);
            String message =this.nickName+" has joined in!"; 
            try {
				broadcast(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        @Override
        protected void onClose(int status) {
            connections.remove(this);
            String message = this.nickName+" has left!" ;
            try {
				broadcast(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		@Override
		protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
			// TODO Auto-generated method stub
			
		}
		@Override
		protected void onTextMessage(CharBuffer arg0) throws IOException {
			// TODO Auto-generated method stub
			String filteredMessage = String.format("%s: %s",
                    this.nickName, HTMLFilter.filter(arg0.toString()));
            broadcast(filteredMessage);
		}
		private void broadcast(String message) throws IOException{
			for(ChatMessageInbound cmi:connections){
				CharBuffer cBuffer=CharBuffer.wrap(message);
				cmi.getWsOutbound().writeTextMessage(cBuffer);
			}
		}
	}
	@Override
	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		this.session=arg0;
	}
}
